import { Injectable, UseFilters } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Between, Like, Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { School } from '../school/entities/school.entity';
import { CreateUserDto, GetUserPage, LoginDto, UpdatePassWordDto, UpdateUserInfoDto } from './dto/user.dto';
import { getPagination, throwHttp } from 'src/utlis';
import { equals, isEmpty, isNil } from 'ramda';
import { HttpExceptionFilter } from 'src/common/http-exception.filter';
import { Status } from 'src/dictionaries/index.enum';
import { compareSync, hashSync } from 'bcryptjs';
import { TokenDto, getTokenInfo } from 'src/common/auth/constants';
import { isTrue } from 'src/utlis/tools';
import { JwtService } from '@nestjs/jwt';
import { SchoolService } from '../school/school.service';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private readonly jwtService: JwtService,
    // private readonly schoolService: SchoolService,
  ) { }
  /** 分页 */
  async getUserPage(params: GetUserPage) {
    try {
      const {
        createTimeStart,
        createTimeEnd,
        updateTimeEnd,
        updateTimeStart,
      } = params;
      const { pageSize, pageNum } = getPagination({
        pageSize: params.pageSize,
        pageNum: params.pageNum,
      });
      const where: GetUserPage = {
        username: Like(`%${params.username || ''}%`),
        account: Like(`%${params.account || ''}%`),
        status: params.status,
        email: params.email,
        phone: params.phone,
        gender: params.gender,
        id: params.id,
      };
      // 创建时间筛选
      if (!isNil(createTimeStart) && !isNil(createTimeEnd)) {
        where.createDate = Between(createTimeStart, createTimeEnd);
      }
      // 更新时间筛选
      if (!isNil(updateTimeStart) && !isNil(updateTimeEnd)) {
        where.updateDate = Between(updateTimeStart, updateTimeEnd);
      }
      const [data, total] = await this.userRepository.findAndCount({
        where,
        cache: true,
        skip: pageNum * pageSize,
        take: pageSize,
        order: { createDate: 'DESC' },
      });
      return {
        data,
        total,
        pageSize,
        pageNum: pageNum + 1,
      };
    } catch (error) {
      throwHttp(error.message);
    }
  }

  /** 登录 */
  @UseFilters(new HttpExceptionFilter())
  async login(params: LoginDto) {
    try {
      const { username, password } = params;
      const user = await this.userRepository
        .createQueryBuilder("user").where('user.account = :username OR user.email = :username', { username })
        .select(['user.email', 'user.password', 'user.id', 'user.status', 'user.username']).getOne();
      if (!user) {
        throwHttp('用户不存在');
      }
      if (!compareSync(password, user.password)) {
        throwHttp('用户名或密码不正确');
      }
      if (equals(user.status, Status.DISABLED)) {
        throwHttp('该账号已被禁用，请联系管理员处理');
      }
      /** 更新登录时间 */
      await this.userRepository
        .createQueryBuilder()
        .update(User)
        .set({
          loginDate: new Date(),
        })
        .where('id = :id', { id: user.id })
        .execute();
      const payload = {
        username: user.username,
        email: user.email,
        userId: user.id,
      };
      delete user.password
      // 把信息存在token
      return {
        token: this.jwtService.sign(payload),
        ...user
      };
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 注册 */
  async createUser(userData: CreateUserDto): Promise<string> {
    try {
      const userInfo = await this.userRepository.findOne({
        where: { account: userData.account },
      });
      if (!isNil(userInfo)) {
        throwHttp('用户已存在');
        return
      }
      const user = new User()
      user.email = userData.email
      user.username = userData.username
      user.hometown = userData.hometown
      user.address = userData.address
      user.password = userData.password
      user.phone = userData.phone
      user.account = userData.account
      user.avatar = userData.avatar
      const result = await this.userRepository.manager.save(user);

      if (!isEmpty(result)) {
        return `注册成功`;
      }
      throwHttp('注册失败');
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 获取用户分类详情 */
  @UseFilters(new HttpExceptionFilter())
  async getUserById(id: number) {
    try {
      return await this.userRepository.findOne({
        where: { id },
        cache: true,
      });
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 修改密码 */
  @UseFilters(new HttpExceptionFilter())
  async updatePassWord(params: UpdatePassWordDto, headers) {
    try {

      const { old_password, new_password } = params;
      const user = getTokenInfo(this.jwtService, headers)
      const userInfo = await this.userRepository.findOne({
        where: { id: user.userId, status: Status.DISABLED },
        select: ['password'],
      });
      if (isNil(userInfo)) {
        throwHttp('用户不存在');
        return;
      }
      if (!compareSync(old_password, userInfo.password)) {
        throwHttp('登录密码不正确');
        return
      }
      if (compareSync(new_password, userInfo.password)) {
        throwHttp('新密码不能与旧密码一致');
        return
      }
      const { affected } = await this.userRepository
        .createQueryBuilder()
        .update(User)
        .set({
          password: await hashSync(new_password),
        })
        .where('id = :id', { id: user.userId })
        .execute();
      if (affected) {
        return '修改成功';
      }
      throwHttp('修改失败');
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 更新用户信息 */
  async updateUser(body: UpdateUserInfoDto, headers) {
    try {
      const { username, phone, avatar, hometown, address, gender } = body
      const user = getTokenInfo(this.jwtService, headers)
      const userInfo = await this.userRepository.findOne({
        where: { id: user.userId, status: Status.ENABLED },
        select: ['id'],
      });
      if (isNil(userInfo)) {
        throwHttp('用户不存在');
        return;
      }
      const { affected } = await this.userRepository
        .createQueryBuilder()
        .update(User)
        .set({
          username, phone, avatar, hometown, address, gender
        })
        .where('id = :id', { id: user.userId })
        .execute();
      if (affected) {
        return '用户信息修改成功';
      }
      throwHttp('用户信息修改失败');
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 绑定学校 */
  async bindSchool(userId: number, schoolId: number) {
    const user = await this.userRepository.findOne({
      where: { id: userId }
    });
    // const school = await this.schoolService;

    // if (!user || !school) {
    //   return undefined; // 用户或学校不存在，返回 undefined
    // }

    // user.school = school;
    // return this.userRepository.save(user);
  }
}
